# -*- coding: utf-8 *-*

#   This file is part of Sql-Rice.
#
#    Sql-Rice is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Sql-Rice is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Sql-Rice; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

import tools.ricer
import gui
import sql_parse
import rules


def to_json(obj):
    if obj is None or obj.__class__.__name__ in __builtins__:
        return obj
    else:
        value = {'__class__': obj.__class__.__name__}
        for k, v in obj.__dict__.items():
            value[k] = to_json(v)
        return value


_serial = {'Ricer': tools.ricer.Ricer,
         'WidgetInfo': gui.WidgetInfo,
         'Sentence': sql_parse.Sentence,
         'TextLength': rules.TextLength,
         'DataDict': sql_parse.DataDict,
         'Field': sql_parse.Field,
         'Table': sql_parse.Table}


def from_json(obj):
    if isinstance(obj, dict):
        if u'__class__' in obj:
            classname = obj[u'__class__']
            create = _serial[classname]
            ret = create()
            for k, v in obj.items():
                if k != '__class__':
                    v = from_json(v)
                    setattr(ret, k, v)
        else:
            ret = {}
            for k, v in obj.items():
                ret[k] = from_json(v)
        return ret
    elif isinstance(obj, list):
        return [from_json(v) for v in obj]
    else:
        return obj
